package kr.shincooper.funnyhome.common.springutil;

import java.io.EOFException;
import java.io.IOException;

import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;

/**
 * 
 * <pre>
 * Custom MappingJacksonHttpMessageConverter
 * </pre>
 *
 * @author bluemirr5@gamil.com
 * @version 0.1
 */
public class CustomMappingJacksonHttpMessageConverter extends MappingJacksonHttpMessageConverter {
	
	/**
	 * 
	 * <pre>
	 * JSON을 Deserialize 할 때 정의되지 않은 필드 에러 세팅
	 * true 일 경우 에러발생, false 일 경우 정의되지 않은 필드 무시
	 *
	 * history
	 * 2013. 5. 16. bluemirr5@gamil.com
	 * 처음 개발
	 * </pre>
	 *
	 * @since 2013. 5. 16.
	 * @param state
	 */
	public void setFailOnUnknownProperties(boolean state){
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, state);
		setObjectMapper(objectMapper);
	}
	
	/**
	 * 
	 * <pre>
	 * java.io.EOFException 에 대해서도 HttpMessageNotReadableException으로 치환하기 위해 오버라이드 했음
	 * </pre>
	 *
	 * @author bluemirr5@gamil.com
	 * @since 2013. 8. 28.
	 *
	 * @param clazz
	 * @param inputMessage
	 * @return Object
	 * @throws IOException
	 * @throws HttpMessageNotReadableException
	 */
	@Override
	protected Object readInternal(
		Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		
		JavaType javaType = getJavaType(clazz);
		
		try{
			return getObjectMapper().readValue(inputMessage.getBody(), javaType);
		}catch(JsonProcessingException ex){
			throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
		}catch (EOFException ex){
			throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
		}
	}
	
}
